// Global vars used in the game
var CANVAS_HEIGHT;
var CANVAS_WIDTH;
var KEY_DOWN = {};
var PLAYER_COLORS = [
	[181, 121, 0],
	[121, 0, 181],
	[121, 181, 0],
	[0, 181, 121],
	[0, 121, 181],
	[181, 0, 121],
	[200, 0, 0],
	[255, 255, 255],
	[0, 0, 0],
];
var SNAKES = {};
var SCORES = {};
var NUM_SNAKES = 0;

// Handle key down and up.
$(document).keydown( function(e) {
	var code = e.keyCode;
	KEY_DOWN[code] = true;
});
$(document).keyup( function (e) {
	var code = e.keyCode;
	KEY_DOWN[code] = false;
});

$(document).ready(function(){
	// Add new player
	$("#addPlayer").click(function(){
		var playerNum = $(".playerControlls").length;
		
		if( typeof(PLAYER_COLORS[ playerNum +1 ]) == "undefined" ){ $(this).hide(); }
		var c = PLAYER_COLORS[ playerNum ];
		var rgb = "rgb(" + c[0] + "," + c[1] + "," + c[2] + ")";

		$("#addPlayer").before(
			$('<label/>', { 
				text: 'Player ' + (playerNum+1), 
				css: {color: rgb}
			}),
			$('<br>'),
			$('<input/>', { type: 'text', 'class': 'text playerControlls', id: 'player' + playerNum }),
			$('<br>')
		);
		$('.playerControlls:last').focus();
	});
	// Handle input into the playerController
	$(".playerControlls").live('keyup', function(e){
		if( !$(this).data()['left'] ){
			$(this).val('Left: ' + codeToString(e.keyCode) );
			$(this).data('left', e.keyCode);
		} else if( ! $(this).data()['right'] ){
			var leftKey = codeToString($(this).data()['left']);
			$(this).val( 'Left: ' + leftKey + '; Right: ' + codeToString(e.keyCode) );
			$(this).data('right', e.keyCode);
		} else {
			$(this).val('');
			$(this).data( 'left', false ).data( 'right', false );
		}
	});

	// run it!
	$('#start').click(function(e){
		runAuchtung();
	})
	
});